import {
    Feedback
} from './feedback.model'
import {
    Config
} from '../../utils/config'
import Toast from '@vant/weapp/toast/toast'
const feedback = new Feedback()
Page({
    /**
     * 页面的初始数据
     */
    data: {
        fileList: [],
        images: []
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad() {

    },

    /**
     * 选择并上传图片
     * @param {*} option
     */
    afterRead(option) {
        let that = this
        const file = option.detail.file,
            url = Config.baseUrl + 'image',
            promise = [],
            images = that.data.images,
            fileList = that.data.fileList
        for (let i = 0; i < file.length; i++) {
            let filePath = [file[i].path],
                upload = feedback.uploadFile(url, filePath)
            promise.push(upload)
        }
        Promise.all(promise).then((res) => {
            wx.hideLoading()
            for (let j = 0; j < res.length; j++) {
                let data = JSON.parse(res[j].data)
                images.push(data.path)
                fileList.push({
                    url: data.allPath
                })
            }
            that.setData({
                images: images,
                fileList: fileList
            })
        }).catch((err) => {
            console.error(err)
        })
    },

    /**
     * 删除图片
     * @param {*} option
     */
    deleteRead(option) {
        let that = this,
            newFileList = that.data.fileList,
            newImages = that.data.images
        newFileList.splice(option.detail.index, 1)
        newImages.splice(option.detail.index, 1)
        that.setData({
            fileList: newFileList,
            images: newImages
        })
    },

    /**
     * 超过设置最大尺寸
     */
    oversize() {
        Toast('请上传2M以内图片')
    },

    /**
     * 提交意见
     * @param {*} options
     */
    doSubmit(options) {
        let that = this,
            value = options.detail.value,
            images = {
                images: that.data.images
            },
            param = {
                ...value,
                ...images
            }
        if (!value.info) {
            Toast.fail('内容为空')
            return false
        }
        feedback.insertFeedbackData(param).then(() => {
            Toast({
                type: 'success',
                message: '提交成功',
                onClose: () => {
                    wx.switchTab({
                        url: '/pages/my/my'
                    })
                },
            })
        })
    }
})